﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BCCommon;
using System.Text;
using System.Net;
using Microsoft.AspNetCore.Mvc;
using BCDto.CRM.EnterpriseInfomation;
using BCTMSRESTful.Configs;
using BCService.Utils;
using BCService.CRM.EnterpriseInfomation;
using Microsoft.AspNetCore.Http;
using System.IO;
using BCDto.UploadHandleComponent;
using BCService.UploadHandleComponent;
using BCDto.Tools;

namespace BCTMSRESTful.Controllers.Management.CRM.EnterpriseInfomation
{
    /// <summary>
    /// 企业信息
    /// </summary>
    [ApiExplorerSettings(GroupName = "CRMAdmin")]
    [Route("api/v1/sim/[controller]")]
    public class EnterpriseInfomationController : ManagementBaseController
    {
        private readonly IEnterpriseInfomationService enterpriseInfomationService;
        private readonly IUploadFileInfoHandleService uploadFileInfoHandleService;
        public EnterpriseInfomationController(IEnterpriseInfomationService enterpriseInfomationService, IUploadFileInfoHandleService uploadFileInfoHandleService)
        {
            this.enterpriseInfomationService = enterpriseInfomationService;
            this.uploadFileInfoHandleService = uploadFileInfoHandleService;
        }

        #region 添加企业信息
        /// <summary>
        ///  添加企业信息
        /// </summary>
        /// <param name="requestDto">企业信息信息</param>
        /// <response code="201">添加企业信息成功</response>
        /// <response code="400">请求参数或输入的数据不正确。</response>
        /// <response code="500">服务器发生错误。</response>
        /// <response code="501">某些功能尚未实现。</response>
        /// <returns></returns>
        [HttpPost]
        [Log("添加企业信息")]
        [ProducesResponseType(typeof(EnterpriseInfomationDto), 201)]
        public IActionResult Post(
            [FromBody]EnterpriseInfomationRequestDto requestDto)
        {
            var result = this.enterpriseInfomationService.Add(requestDto);
            return StatusCode((int)HttpStatusCode.Created, result);
        }
        #endregion

        #region 修改企业信息
        /// <summary>
        ///  修改企业信息
        /// </summary>
        /// <param name="enterpriseInfomationId">企业信息Id</param>
        /// <param name="requestDto">企业信息信息</param>
        /// <response code="200">修改企业信息成功</response>
        /// <response code="400">请求参数或输入的数据不正确。</response>
        /// <response code="500">服务器发生错误。</response>
        /// <response code="501">某些功能尚未实现。</response>
        /// <returns></returns>
        [HttpPut("{enterprise_infomation_id}")]
        [Log("修改企业信息")]
        [ProducesResponseType(typeof(EnterpriseInfomationDto), 200)]
        public IActionResult Put([FromRoute(Name = "enterprise_infomation_id")]long enterpriseInfomationId, [FromBody]EnterpriseInfomationRequestDto requestDto)
        {
            EnterpriseInfomationPutDto putDto = requestDto.As<EnterpriseInfomationPutDto>();
            putDto.EnterpriseInfomationId = enterpriseInfomationId;
            return StatusCode((int)HttpStatusCode.OK, this.enterpriseInfomationService.Update(putDto));
        }
        #endregion

        #region 删除企业信息
        /// <summary>
        ///  删除企业信息
        /// </summary>
        /// <param name="enterpriseInfomationId">企业信息Id</param>
        /// <response code="204">删除企业信息成功</response>
        /// <response code="400">请求参数或输入的数据不正确。</response>
        /// <response code="500">服务器发生错误。</response>
        /// <response code="501">某些功能尚未实现。</response>
        /// <returns></returns>
        [HttpDelete("{enterprise_infomation_id}")]
        [Log("删除企业信息")]
        [ProducesResponseType(typeof(NoContentResult), 204)]
        public IActionResult Delete([FromRoute(Name = "enterprise_infomation_id")]long enterpriseInfomationId)
        {
            this.enterpriseInfomationService.Delete(enterpriseInfomationId);
            return StatusCode((int)HttpStatusCode.NoContent);
        }
        #endregion

        #region 获取企业信息
        /// <summary>
        ///  获取企业信息
        /// </summary>
        /// <param name="enterpriseInfomationId">企业信息Id</param>
        /// <response code="200">获取企业信息</response>
        /// <response code="400">请求参数或输入的数据不正确。</response>
        /// <response code="500">服务器发生错误。</response>
        /// <response code="501">某些功能尚未实现。</response>
        /// <returns></returns>
        [HttpGet("{enterprise_infomation_id}")]
        [ProducesResponseType(typeof(EnterpriseInfomationDto), 200)]
        public IActionResult Get([FromRoute(Name = "enterprise_infomation_id")]long enterpriseInfomationId)
        {
            return StatusCode((int)HttpStatusCode.OK, this.enterpriseInfomationService.Get(enterpriseInfomationId));
        }
        #endregion

        #region 获取企业信息列表
        /// <summary>
        ///  获取企业信息列表
        /// </summary>
        /// <response code="200">获取企业信息列表</response>
        /// <response code="400">请求参数或输入的数据不正确。</response>
        /// <response code="500">服务器发生错误。</response>
        /// <response code="501">某些功能尚未实现。</response>
        /// <returns></returns>
        [HttpGet]
        [ProducesResponseType(typeof(IEnumerable<EnterpriseInfomationDto>), 200)]
        public IActionResult GetList()
        {
            return StatusCode((int)HttpStatusCode.OK, this.enterpriseInfomationService.GetList());
        }
        #endregion

        #region 获取企业信息（分页）
        /// <summary>
        ///  获取企业信息（分页）
        /// </summary>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <param name="sortName">排序字段</param>
        /// <param name="ascending">升序</param>
        /// <param name="index">当前页码</param>
        /// <param name="size">当前页大小</param>
        /// <response code="200">获取企业信息（分页）</response>
        /// <response code="400">请求参数或输入的数据不正确。</response>
        /// <response code="500">服务器发生错误。</response>
        /// <response code="501">某些功能尚未实现。</response>
        /// <returns></returns>
        [HttpGet("[action]")]
        [ProducesResponseType(typeof(PageableList<EnterpriseInfomationDto>), 200)]
        public IActionResult Query(
            [FromQuery(Name = "start")]DateTime? start,
            [FromQuery(Name = "end")]DateTime? end,
            [FromQuery(Name = "sort_name")]string sortName,
            [FromQuery(Name = "ascending")]bool? ascending,
            [FromQuery(Name = "index")]int index = 1,
            [FromQuery(Name = "size")]int size = 10)
        {
            return StatusCode((int)HttpStatusCode.OK, this.enterpriseInfomationService.Query(start, end, sortName, ascending, index, size));
        }
        #endregion

        /// <summary>
        /// 导入企业信息Excel。
        /// </summary>
        /// <param name="from">上传文件信息</param>
        /// <response code="200">成功导入的数量。</response>
        /// <response code="401">请求需要认证或者认证信息已过期。</response>
        /// <response code="403">无权访问指定的功能。</response>
        /// <returns></returns>
        [HttpPost("[action]")]
        [ProducesResponseType(typeof(ImportResultDto), 200)]
        public IActionResult Upload([FromForm]IFormCollection from)
        {
            var data = from.Files["data"];
            UploadFileDto uploadFileDto = uploadFileInfoHandleService.Init(from["fileName"], from["usage"], ".jpg");
            if(uploadFileDto.FolderName!="office")
            {
                throw new ArgumentException("导入企业信息仅支持Excel导入!");
            }
            if (data == null || data.Length <= 0)
            {
                return BadRequest("文件错误！");
            }
            string path = uploadFileDto.FilePath;
            using (FileStream fs = new FileStream(path, FileMode.Create))
            {
                data.CopyTo(fs);
                fs.Flush();
            }

            string importType = "TianYanCha";
            if (from.Any(p => p.Key.Equals("remark")))
            {
                importType = from["remark"];
            }
            else
            {
                throw new ArgumentException("缺少remark参数，此参数支持的值有：TianYanCha,GeneralTemplate");
            }
            var result = this.enterpriseInfomationService.ImportEnterpriseFile(importType, path);
            result.Src = uploadFileDto.WebsiteFullName;
            return Ok(result);
        }
    }
}

